package com.example.education.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.education.Bean.News;
import com.example.education.Mapper.NewsMapper;
import com.example.education.service.NewsService;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.model.PreferenceArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 姚
 * @since 2023-04-12
 */
@Service
@Transactional
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements NewsService {

    @Autowired
    private NewsMapper newsMapper;


    public ArrayList<News> recommendNews(String country) {
        ArrayList<News> news = newsMapper.selectAll(country);
        return news;
    }

    //通过mahout推荐大量新闻
    public void recommend(DataModel dataModel) {
        LongPrimitiveIterator iterator = null;
        try {
            iterator = dataModel.getUserIDs();
        } catch (TasteException e) {
            throw new RuntimeException(e);
        }
        while (iterator.hasNext()) {
            long userId = iterator.nextLong();
            PreferenceArray userPreferences = null;
            try {
                userPreferences = dataModel.getPreferencesFromUser(userId);
            } catch (TasteException e) {
                throw new RuntimeException(e);
            }
            for (int i = 0; i < userPreferences.length(); i++) {
                long itemId = userPreferences.getItemID(i);
                System.out.println("用户" + userId + "喜欢" + itemId);
            }
        }
    }

    @Override
    public DataModel getDataModel() {
        return null;
    }

    @Override
    public ArrayList<News> selectAllNews() {
        return newsMapper.selectAllNews();
    }


    //根据你现在的留学阶段推荐新闻
    @Override
    public ArrayList<News> recommendNewsByStage(String stage) {

        if (stage == null) {
            return newsMapper.selectAllNews();
        } else {
            return newsMapper.recommendNewsByStage(stage);
        }

    }


}
